package com.partner.match.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.partner.match.common.ErrorCode;
import com.partner.match.constant.TeamConstant;
import com.partner.match.constant.UserConstant;
import com.partner.match.exception.BusinessException;
import com.partner.match.mapper.TeamMapper;
import com.partner.match.mapper.UserMapper;
import com.partner.match.mapper.UserTeamMapper;
import com.partner.match.model.dto.team.CreatedTeamReq;
import com.partner.match.model.dto.team.JoinTeamReq;
import com.partner.match.model.dto.team.QueryTeamResp;
import com.partner.match.model.dto.team.UpdateTeamReq;
import com.partner.match.model.entity.Team;
import com.partner.match.model.entity.User;
import com.partner.match.model.entity.UserTeam;
import com.partner.match.model.enums.TeamStateEnum;
import com.partner.match.model.enums.UserRoleEnum;
import com.partner.match.model.vo.LoginUserVO;
import com.partner.match.model.vo.UserVO;
import com.partner.match.service.TeamService;
import com.partner.match.service.UserTeamService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author jzz
 * @description 针对表【team(队伍表)】的数据库操作Service实现
 * @createDate 2025-01-25 10:26:45
 */
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
        implements TeamService {

    @Resource
    private TeamMapper teamMapper;

    @Resource
    private UserTeamMapper userTeamMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserTeamService userTeamService;

    @Resource
    private RedissonClient redissonClient;

    @Override
    public Long addTeam(CreatedTeamReq teamReq, Long userId) {
        if (ObjectUtil.isNull(teamReq)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍信息为空");
        }

        Team team = BeanUtil.copyProperties(teamReq, Team.class);

        // 校验过期时间
        Date expireTime = team.getExpireTime();
        if (expireTime.before(new Date())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "过期时间必须在当前时间之后");
        }

        // 校验并加密密码
        String encryptPassword = "";
        if (Objects.equals(teamReq.getStatus(), TeamStateEnum.ENCRYPT.getValue())) {
            // 密码长度限制
            if (teamReq.getPassword().length() > 15 || teamReq.getPassword().length() < 4) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
            }
            encryptPassword = DigestUtils.md5DigestAsHex((TeamConstant.SALT + teamReq.getPassword()).getBytes());
            team.setPassword(encryptPassword);
        }

        // 校验创建队伍个数
        QueryWrapper<Team> teamQW = new QueryWrapper<>();
        teamQW.eq(Team.USER_ID, userId);
        Long count = teamMapper.selectCount(teamQW);
        if (count >= 5) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "每个用户最多创建5个队伍");
        }

        // 设置用户信息
        team.setUserId(userId);
        boolean saved = this.save(team);
        if (!saved) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍失败");
        }
        return team.getTeamId();
    }


    @Override
    public Page<QueryTeamResp> selectTeams(Long currentPage, Long pageSize, String teamName) {
        QueryWrapper<Team> teamQW = new QueryWrapper<>();
        if (StrUtil.isNotBlank(teamName)) {
            teamQW.like(Team.TEAM_NAME, teamName);
        }
        teamQW.ge(Team.EXPIRE_TIME, new Date());
        // 只有管理员才可以看到非公开队伍
        User loginUser = (User) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        if (!Objects.equals(loginUser.getUserRole(), UserRoleEnum.ADMIN.getValue())) {
            teamQW.ne(Team.STATUS, TeamStateEnum.PRIVATE.getValue());
        }
        return getQueryTeamRespPage(currentPage, pageSize, teamQW);
    }

    @Override
    public void updateTeam(UpdateTeamReq updateTeamReq) {
        // 队伍信息是否存在
        Team team = teamMapper.selectById(updateTeamReq.getTeamId());
        if (ObjectUtil.isNull(team)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 只有管理员和队长可以修改队伍信息
        User user = (User) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        if (!Objects.equals(user.getUserId(), team.getUserId()) ||
                !Objects.equals(user.getUserRole(), UserRoleEnum.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 校验过期时间
        Date expireTime = updateTeamReq.getExpireTime();
        if (expireTime.before(new Date())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "过期时间必须在当前时间之后");
        }
        team.setExpireTime(expireTime);

        // 校验队伍状态
        Integer status = updateTeamReq.getStatus();
        String password = updateTeamReq.getPassword();
        team.setStatus(status);
        if (Objects.equals(status, TeamStateEnum.PUBLIC.getValue())) {
            team.setPassword(null);
        }
        if (Objects.equals(status, TeamStateEnum.ENCRYPT.getValue())) {
            if (ObjectUtil.isNull(password)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "加密的队伍必须有密码");
            }
            password = DigestUtils.md5DigestAsHex((TeamConstant.SALT + password).getBytes());
            team.setPassword(password);
        }
        if (Objects.equals(status, TeamStateEnum.PRIVATE.getValue())) {
            if (ObjectUtil.isNull(password)) {
                team.setPassword(null);
            }
            password = DigestUtils.md5DigestAsHex((TeamConstant.SALT + password).getBytes());
            team.setPassword(password);
        }
        // 校验最大人数
        Integer maxNum = updateTeamReq.getMaxNum();
        QueryWrapper<UserTeam> userTeamQW = new QueryWrapper<>();
        userTeamQW.eq(Team.TEAM_ID, team.getTeamId());
        Long count = userTeamMapper.selectCount(userTeamQW);
        if (maxNum < count) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最大人数必须大于队伍当前人数");
        }
        team.setMaxNum(maxNum);

        boolean updated = this.updateById(team);
        if (!updated) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改失败");
        }
    }

    @Override
    public Long joinTeam(JoinTeamReq teamReq, long userId) {
        Long teamId = teamReq.getTeamId();
        Integer status = teamReq.getStatus();
        String password = teamReq.getPassword();
        UserTeam userTeam = new UserTeam();

        // 加入分布式
        RLock lock = redissonClient.getLock("match:join_team");
        try {
            while (true) {
                boolean tryLock = lock.tryLock(0, -1, TimeUnit.MILLISECONDS);
                if (tryLock) {
                    // 数据是否存在
                    Team team = teamMapper.selectById(teamId);
                    if (ObjectUtil.isNull(team)) {
                        throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
                    }
                    userTeam.setTeamId(teamId);

                    // 队伍人员是否已满
                    QueryWrapper<UserTeam> userTeamQW = new QueryWrapper<>();
                    userTeamQW.eq(Team.TEAM_ID, teamId);
                    Long count = userTeamMapper.selectCount(userTeamQW);
                    if (count >= team.getMaxNum()) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "队伍人数已满");
                    }

                    // 加入时间是否过期
                    Date expireTime = team.getExpireTime();
                    if (expireTime.before(new Date())) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "队伍已过期");
                    }

                    // 是否重复加入
                    userTeamQW.eq(UserTeam.USER_ID, userId);
                    UserTeam one = userTeamMapper.selectOne(userTeamQW);
                    if (ObjectUtil.isNotNull(one)) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "不可重复加入");
                    }

                    // 校验最大加入队伍数
                    LambdaQueryWrapper<UserTeam> userTeamLQW = new LambdaQueryWrapper<>();
                    userTeamLQW.eq(UserTeam::getUserId, userId);
                    Long joinCnt = userTeamMapper.selectCount(userTeamLQW);
                    if (joinCnt >= TeamConstant.MAX_JOIN) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "最大加入和创建的队伍数不超过8个");
                    }
                    // 是否需要密码
                    if (Objects.equals(status, TeamStateEnum.ENCRYPT.getValue())) {
                        if (ObjectUtil.isNull(password)) {
                            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码为空");
                        }
                        password = DigestUtils.md5DigestAsHex((TeamConstant.SALT + password).getBytes());
                        if (!password.equals(team.getPassword())) {
                            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
                        }
                    }
                    userTeam.setUserId(userId);
                    int insert = userTeamMapper.insert(userTeam);
                    if (insert <= 0) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "加入失败");
                    }
                    return userTeam.getId();
                }
            }
        } catch (InterruptedException e) {
            log.error("get lock fail", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return 0L;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dissolveTeam(Long teamId) {
        if (ObjectUtil.isNull(teamId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 队伍是否存在
        Team team = teamMapper.selectById(teamId);
        if (ObjectUtil.isNull(team)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是不是队长
        long userId = StpUtil.getLoginIdAsLong();
        if (Objects.equals(team.getUserId(), userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        QueryWrapper<UserTeam> userTeamQW = new QueryWrapper<>();
        userTeamQW.eq(UserTeam.TEAM_ID, teamId);
        int deleted = userTeamMapper.delete(userTeamQW);
        if (deleted <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "解散队伍失败");
        }
        int deleteById = teamMapper.deleteById(teamId);
        if (deleteById <= 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "删除队伍失败");
        }
    }

    @Override
    public Page<QueryTeamResp> selectTeamSelf(Long currentPage, Long pageSize) {
        User user = (User) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        QueryWrapper<Team> teamQW = new QueryWrapper<>();
        teamQW.eq(Team.USER_ID, user.getUserId());
        return getQueryTeamRespPage(currentPage, pageSize, teamQW);
    }

    @Override
    public Page<QueryTeamResp> selectJoinTeamSelf(Long currentPage, Long pageSize) {
        User user = (User) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        QueryWrapper<UserTeam> userTeamQW = new QueryWrapper<>();
        userTeamQW.eq(UserTeam.USER_ID, user.getUserId());
        Page<UserTeam> userTeamPage = userTeamService.page(new Page<>(currentPage, pageSize), userTeamQW);

        // 获取用户加入的队伍Id列表
        List<Long> teamIds = userTeamPage.getRecords().stream().map(UserTeam::getTeamId).collect(Collectors.toList());

        QueryWrapper<Team> teamQW = new QueryWrapper<>();
        teamQW.in(Team.TEAM_ID, teamIds);

        return getQueryTeamRespPage(currentPage, pageSize, teamQW);
    }


    private Page<QueryTeamResp> getQueryTeamRespPage(Long currentPage, Long pageSize, QueryWrapper<Team> teamQW) {
        Page<Team> teamPage = this.page(new Page<>(currentPage, pageSize), teamQW);

        Page<QueryTeamResp> queryTeamRespPage = new Page<>(currentPage, pageSize);
        List<QueryTeamResp> teamRespList = new ArrayList<>();
        for (Team team : teamPage.getRecords()) {
            QueryTeamResp queryTeamResp = new QueryTeamResp();
            queryTeamResp.setTeam(team);

            List<UserTeam> userTeams = userTeamMapper.selectList(new QueryWrapper<UserTeam>().eq(UserTeam.TEAM_ID, team.getTeamId()));
            List<UserVO> userVOList = userTeams.stream().map(item -> {
                User tempUser = userMapper.selectById(item.getUserId());
                return BeanUtil.copyProperties(tempUser, UserVO.class);
            }).collect(Collectors.toList());

            queryTeamResp.setUserList(userVOList);
            teamRespList.add(queryTeamResp);
        }

        queryTeamRespPage.setRecords(teamRespList);
        queryTeamRespPage.setTotal(teamPage.getTotal());
        queryTeamRespPage.setSize(teamPage.getSize());
        queryTeamRespPage.setCurrent(teamPage.getCurrent());

        return queryTeamRespPage;
    }
}




